﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace h2100
{
    /// <summary>
    /// Action button thực hiện các hành động khi chơi game: nâng cấp, tấn công ...
    /// </summary>
    public class hActionButton:hClickableRect
    {
        private string _actionstring;
        public string ActionString
        {
            get { return _actionstring; }
            set { _actionstring = value; }
        }

        private int _lvl=0;
        public int Level
        {
            get { return _lvl; }
            set { _lvl = value; }
        }

        private int _maxlvl=0;
        public int MaxLevel
        {
            get { return _maxlvl; }
            set { _maxlvl = value; }
        }

        private int _action;
        public int Action
        {
            get { return _action; }
            set { _action = value; }
        }

        private int[] _subActions;
        public int[] SubActionsIndexes
        {
            get { return _subActions; }
            set { _subActions = value; }
        }

        private List<hActionButton> _lstSubActions;
        public List<hActionButton> SubActionsList
        {
            get { return _lstSubActions; }
            set { _lstSubActions = value; }
        }

        private bool _wait4Target = false;
        public bool Wait4Target
        {
            get { return _wait4Target; }
            set { _wait4Target = value; }
        }

        private int _cost = 0;
        public int Cost
        {
            get { return _cost; }
            set { _cost = value; }
        }

        private bool _selecting = false;
        public bool Selecting
        {
            get { return _selecting; }
            set { _selecting = value; }
        }

        private bool _isActionSuccess = false;

        //private Texture2D txt_undefined;
        //private Texture2D txt_upgrade;
        //private Texture2D txt_disable;
        //private Texture2D txt_upgrade_weapon;
        //private Texture2D txt_upgrade_armor;
        //private Texture2D txt_build;
        //private Texture2D txt_attack;
        //private Texture2D txt_scan;
        //private Texture2D txt_build_house;
        //private Texture2D txt_build_bunker;
        //private Texture2D txt_build_lab;
        //private Texture2D txt_build_energyprocessor;
        //private Texture2D txt_build_rawresourceprocessor;
        //private Texture2D txt_build_airprocessor;
        //private Texture2D txt_build_altar;

        private string _tooltipText = "";
        public string TooltipText
        {
            get { return _tooltipText; }
            set { _tooltipText = value; }
        }

        public hActionButton()
        {
 
        }

        public hActionButton(ContentManager content, string strtexture, float x, float y, hText console)
        {
            Console = console;
            createActionButton(content, strtexture, x, y);
            Text = "";
            _command = hGlobal.Command.Action;
            _action = -1;
        }

        public override void moveOnClicked(bool undo)
        {
            if(Action!=-1)
            {
                if (undo)
                {
                    X -=2;
                    Y -=2;
                }
                else 
                {
                    X += 2.0f / 10;
                    Y += 2.0f / 10;                
                }
            }
        }

        public override hVisibleGameEntity clone()
        {
            hVisibleGameEntity newObject = new hActionButton();
            newObject._nsprite = this._nsprite;
            newObject._sprite = new hSprite[this._nsprite];
            for (int i = 0; i < this._nsprite; i++)
            {
                newObject._sprite[i] = new hSprite(this._sprite[i].Texture);
            }

            newObject.X = this.X;
            newObject.Y = this.Y;
            newObject.Width = this.Width;
            newObject.Height = this.Height;
            ((hActionButton)newObject).TooltipText = this.TooltipText;
            ((hActionButton)newObject).Cost = this.Cost;
            ((hActionButton)newObject).ActionString = this.ActionString;
            ((hActionButton)newObject).SubActionsIndexes = this.SubActionsIndexes;
            ((hActionButton)newObject).MaxLevel = this.MaxLevel;
            ((hActionButton)newObject)._sprite[0] = this._sprite[0];
            ((hActionButton)newObject).X = this.X;
            ((hActionButton)newObject).Y = this.Y;
            ((hActionButton)newObject).Console = this.Console;
            ((hActionButton)newObject).Command = hGlobal.Command.Action;
            ((hActionButton)newObject).SubActionsList = new List<hActionButton>();
            return newObject;
        }

        private void applyAction(hParams args, hVisibleGameEntity obj)
        {
            String strObjType = "";
            if (obj != null)
            {
                strObjType = obj.GetType().Name;
            }

            string action = ActionString.Split(' ')[1];
            switch (action)
            {
                case "+":
                    switch (strObjType)
                    {
                        case "hStructure":
                            switch (ActionString.Split(' ')[2])
                            {
                                case "power":
                                    ((hStructure)obj).Power += int.Parse(ActionString.Split(' ')[3]);
                                    _isActionSuccess = true;
                                    break;
                                case "energy":
                                    ((hStructure)obj).Energy += int.Parse(ActionString.Split(' ')[3]);
                                    _isActionSuccess = true;
                                    break;
                            }
                            break;
                        case "hUnit":
                            switch (ActionString.Split(' ')[2])
                            {
                                case "power":
                                    ((hUnit)obj).Power += int.Parse(ActionString.Split(' ')[3]);
                                    _isActionSuccess = true;
                                    break;
                                case "energy":
                                    ((hUnit)obj).Energy += int.Parse(ActionString.Split(' ')[3]);
                                    _isActionSuccess = true;
                                    break;
                            }
                            break;
                    }
                    break;
                case "-":
                    switch (strObjType)
                    {
                        case "hStructure":
                            switch (ActionString.Split(' ')[2])
                            {
                                case "power":

                                    ((hStructure)obj).Power -= int.Parse(ActionString.Split(' ')[3]);
                                    _isActionSuccess = true;
                                    break;
                                case "energy":

                                    ((hStructure)obj).Energy -= int.Parse(ActionString.Split(' ')[3]);
                                    _isActionSuccess = true;
                                    break;
                            }
                            break;
                        case "hUnit":
                            switch (ActionString.Split(' ')[2])
                            {
                                case "power":
                                    ((hUnit)obj).Power -= int.Parse(ActionString.Split(' ')[3]);
                                    _isActionSuccess = true;
                                    break;
                                case "hUnit":
                                    ((hStructure)obj).Energy -= int.Parse(ActionString.Split(' ')[3]);
                                    _isActionSuccess = true;
                                    break;
                            }
                            break;
                    }
                    break;
                case "build":                 

                    if (args.IsMouseOverControlPanel)
                    {
                        args.SubCursor = null;
                        break;
                    }

                    bool matchterrain = false;
                    hStructure prototype = ((hStructure)(args.StructureManager.Prototypes[int.Parse(ActionString.Split(' ')[3])]));
                    for (int i = 0; i < prototype.TerrainType.Count(); i++)
                    {
                        if (args.HightlightingMapCell != null
                            && args.HightlightingMapCell.Type.Equals(prototype.TerrainType[i])
                            && args.HightlightingMapCell.onFogOfWar == false)
                        {
                            matchterrain = true;
                        }
                    }
                    args.SubCursor = args.StructureManager.Prototypes[int.Parse(ActionString.Split(' ')[3])]._sprite[0].Texture[0];
                    if (matchterrain && args.HightlightingMapCell.isFreeToBuild)
                    {
                        args.SubCursorColor = Color.Green;
                    }
                    else
                    {
                        args.SubCursorColor = Color.Red;
                    }
                    if ((args.SelectedMapCell != null)
                        && matchterrain
                        && (args.SelectedMapCellPosition.X >= 0 && args.SelectedMapCellPosition.X <= hGlobal.ScreenWidth
                                && args.SelectedMapCellPosition.Y >= 0 && args.SelectedMapCellPosition.Y <= hGlobal.ScreenHeight - hGlobal.ControlPanelHeight
                                && args.SelectedMapCell.isFreeToBuild))
                    {
                        args.StructureManager.createObject(int.Parse(ActionString.Split(' ')[3]), args.SelectedMapCellIndexRowColumn.X, args.SelectedMapCellIndexRowColumn.Y);
                        args.ControlPhase = hGlobal.ControlPhase.Action;
                        this.Selecting = false;
                        args.SubCursor = null;
                        _isActionSuccess = true;

                    }
                    break;
                case "createunit":
                    if (args.IsMouseOverControlPanel)
                    {
                        args.SubCursor = null;
                        break;
                    }

                    matchterrain = false;
                    hUnit uprototype = ((hUnit)(args.UnitManager.Prototypes[int.Parse(ActionString.Split(' ')[3])]));
                    if (args.HightlightingMapCell != null
                        && args.HightlightingMapCell.Type.Equals("NormalTerrain")
                        && args.HightlightingMapCell.onFogOfWar == false)
                    {
                        matchterrain = true;
                    }
                    args.SubCursor = this._sprite[0].Texture[0];
                    if (matchterrain && args.HightlightingMapCell.isFreeToBuild)
                    {
                        args.SubCursorColor = Color.Green;
                    }
                    else
                    {
                        args.SubCursorColor = Color.Red;
                    }
                    if ((args.SelectedMapCell != null)
                        && matchterrain
                        && (args.SelectedMapCellPosition.X >= 0 && args.SelectedMapCellPosition.X <= hGlobal.ScreenWidth
                                && args.SelectedMapCellPosition.Y >= 0 && args.SelectedMapCellPosition.Y <= hGlobal.ScreenHeight - hGlobal.ControlPanelHeight
                                && args.SelectedMapCell.isFreeToBuild))
                    {
                        args.UnitManager.createObject(int.Parse(ActionString.Split(' ')[3]),Mouse.GetState().X , Mouse.GetState().Y);
                        args.ControlPhase = hGlobal.ControlPhase.Action;
                        this.Selecting = false;
                        args.SubCursor = null;
                        _isActionSuccess = true;
                    }
                    break;
                case "attack":
                    args.SubCursor = this._sprite[0].Texture[0];
                    args.SubCursorColor = Color.Yellow;
                        if ((args.SelectedMapCell != null) && (args.SelectedMapCellPosition.X >= 0 && args.SelectedMapCellPosition.X <= hGlobal.ScreenWidth
                                    && args.SelectedMapCellPosition.Y >= 0 && args.SelectedMapCellPosition.Y <= hGlobal.ScreenHeight - hGlobal.ControlPanelHeight))
                        {
                            if (strObjType.Equals("hUnit"))
                            {
                                ((hUnit)obj).attack(Mouse.GetState().X, Mouse.GetState().Y);
                            }
                            args.Skill.FireStrom(obj.Center, new Vector2(Mouse.GetState().X,Mouse.GetState().Y), int.Parse(ActionString.Split(' ')[3]));
                            args.Skill.update(args, null);
                            if (!args.Skill.OnCast)
                            {
                                if (strObjType.Equals("hUnit"))
                                {
                                    ((hUnit)obj).endAttack();
                                }
                                args.ControlPhase = hGlobal.ControlPhase.Action;
                                this.Selecting = false;
                                args.SubCursor = null;
                                _isActionSuccess = true;
                            }

                        }
                    
                    break;
                case "clearfog":
                    args.SubCursor = this._sprite[0].Texture[0];
                    args.SubCursorColor = Color.Yellow;
                    if (args.Grid.SelectedGrid.X != -1)
                    {
                        args.MapManager.Map.MapCells[args.Grid.SelectedGrid.X, args.Grid.SelectedGrid.Y].onFogOfWar = false;
                        args.ControlPhase = hGlobal.ControlPhase.Action;
                        this.Selecting = false;
                        args.SubCursor = null;
                        _isActionSuccess = true;
                    }
                    break;
                case "repair":
                    break;
                case "move":
                    args.SubCursor = this._sprite[0].Texture[0];
                    args.SubCursorColor = Color.Yellow;
                    if ((args.SelectedMapCell != null)
                       && (args.SelectedMapCellPosition.X >= 0 && args.SelectedMapCellPosition.X <= hGlobal.ScreenWidth
                               && args.SelectedMapCellPosition.Y >= 0 && args.SelectedMapCellPosition.Y <= hGlobal.ScreenHeight - hGlobal.ControlPanelHeight)
                        && args.SelectedMapCell.isFreeToBuild)
                    {
                        if (strObjType.Equals("hUnit"))
                        {
                            ((hUnit)obj).move(Mouse.GetState().X, Mouse.GetState().Y);
                        }
                        else
                        {
                            obj.Center = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
                        }
                        args.ControlPhase = hGlobal.ControlPhase.Action;
                        this.Selecting = false;
                        args.SubCursor = null;
                        _isActionSuccess = true;

                    }
                    break;
                default:
                    break;
            }
        }

        private void performAction(hParams args)
        {         

            if ((MaxLevel == 0) || (MaxLevel > 0 && Level < MaxLevel))
            {                
                _isActionSuccess = false;
                if (!ActionString.Trim().Equals(""))
                {
                    string obj = ActionString.Split(' ')[0];                   
                    switch (obj)
                    {
                        case "global":
                            applyAction(args, null);
                            break;
                        case "this":
                            applyAction(args, args.ActionManager.ActionCaller);
                            break;
                        case "subaction":
                            args.ActionManager.setCurrentActionButtons(SubActionsList);
                            args.ControlPhase = hGlobal.ControlPhase.SubAction;
                            break;
                        case "forall":
                            break;
                        case "forallenemy":
                            break;
                        case "forallstruct":
                            for (int i = 0; i < args.StructureManager.NRows; i++)
                                for (int j = 0; j < args.StructureManager.NColumns; j++)
                                {
                                    if (args.StructureManager.Structures[i, j] != null)
                                    {
                                        applyAction(args, args.StructureManager.Structures[i, j]);
                                    }
                                }
                            break;
                        case "forallenemystruct":
                            break;
                        case "forallunit":
                            break;
                        case "forallenemyunit":
                            break;
                    }
                }
                if (MaxLevel > 0 && _isActionSuccess)
                {
                    Level++;
                }
                if (_isActionSuccess)
                {
                    args.Energy -= Cost;
                }
            }
        }

        public new void update(hParams args, GameTime gameTime)
        {
            base.update(args, gameTime);
            if (this.Hightlighted)
            {
                args.ControlPanel.TooltipText = this.TooltipText + Environment.NewLine + "Cost: " + this.Cost.ToString();
            }

            KeyboardState keyState = Keyboard.GetState();
            if (keyState.IsKeyDown(Keys.Escape))
            {
                args.ControlPhase = hGlobal.ControlPhase.Action;
                this.Selecting = false;
                args.SubCursor = null;
            }

            if (this.Selected || this.Selecting)
            {
                if (Selecting ==false &&
                    ActionString.Split(' ').Count() > 2
                    && ActionString.Split(' ')[2].Equals("target"))
                {
                    Selecting = true;
                    args.SelectedMapCell = null;
                    args.ControlPhase = hGlobal.ControlPhase.Selecting;
                    args.Grid.SelectedGrid = new Point(-1, -1);
                }
                performAction(args);
                if (this.Selected)
                {
                    Selected = false;
                }
            }
        }
    }
}
